import matplotlib
matplotlib.use('Agg')
from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth import login, logout, authenticate
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from.models import Todo, Category, TaskTemplate
from.forms import RegisterForm, TodoForm, CategoryForm, TaskTemplateForm
import matplotlib.pyplot as plt
import io
import base64
from django.db.models.functions import TruncWeek
from django.db.models import Count
import datetime
from django.http import JsonResponse


# 解决matplotlib中文显示问题
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False


# 注册
def register(request):
    if request.method == 'POST':
        form = RegisterForm(request.POST)
        if form.is_valid():
            user = form.save()
            login(request, user)
            return redirect('index')
        else:
            messages.error(request, '注册失败，请检查输入')
    else:
        form = RegisterForm()
    return render(request, 'todo/register.html', {'form': form})


# 登录
def user_login(request):
    if request.method == 'POST':
        form = AuthenticationForm(request, data=request.POST)
        if form.is_valid():
            username = form.cleaned_data.get('username')
            password = form.cleaned_data.get('password')
            user = authenticate(username=username, password=password)
            if user is not None:
                login(request, user)
                return redirect('index')
            else:
                messages.error(request, '用户名或密码错误')
        else:
            messages.error(request, '用户名或密码错误')
    form = AuthenticationForm()
    return render(request, 'todo/login.html', {'form': form})


# 注销
@login_required
def user_logout(request):
    logout(request)
    return redirect('login')


# 首页（带统计图表）
@login_required
def index(request):
    # 获取当前用户的任务，排序将遵循模型中 Meta.ordering 的设置
    todos = Todo.objects.filter(user=request.user)
    completed_count = todos.filter(completed=True).count()
    total_count = todos.count()

    # 生成统计图表
    if total_count > 0:
        labels = ['已完成', '未完成']
        sizes = [completed_count, total_count - completed_count]
        colors = ['#d4edda', '#f8d7da']

        plt.figure(figsize=(5, 3))
        plt.pie(sizes, labels=labels, colors=colors, autopct='%1.1f%%', startangle=90)
        plt.axis('equal')
        plt.title('任务完成情况')

        buffer = io.BytesIO()
        plt.savefig(buffer, format='png')
        buffer.seek(0)
        image_png = buffer.getvalue()
        buffer.close()

        graphic = base64.b64encode(image_png)
        graphic = graphic.decode('utf-8')
    else:
        graphic = None

    return render(request, 'todo/index.html', {
        'todos': todos,
        'graphic': graphic,
        'completed_percentage': (completed_count / total_count * 100) if total_count > 0 else 0
    })

# 新增待办
@login_required
def add_todo(request):
    if request.method == 'POST':
        form = TodoForm(request.POST)
        if form.is_valid():
            todo = form.save(commit=False)
            todo.user = request.user
            todo.save()
            return redirect('index')
    else:
        form = TodoForm()
    return render(request, 'todo/add.html', {'form': form})

# 编辑待办
@login_required
def edit_todo(request, todo_id):
    todo = get_object_or_404(Todo, pk=todo_id, user=request.user)
    if request.method == 'POST':
        form = TodoForm(request.POST, instance=todo)
        if form.is_valid():
            form.save()
            return redirect('index')
    else:
        form = TodoForm(instance=todo)
    return render(request, 'todo/edit.html', {'form': form, 'todo': todo})

# 删除待办
def delete_todo(request, todo_id):
    todo = get_object_or_404(Todo, pk=todo_id)
    todo.delete()
    return redirect('index')

# 分类管理
@login_required
def manage_categories(request):
    categories = Category.objects.filter(user=request.user)
    if request.method == 'POST':
        form = CategoryForm(request.POST)
        if form.is_valid():
            category = form.save(commit=False)
            category.user = request.user
            category.save()
            return redirect('manage_categories')
    else:
        form = CategoryForm()
    return render(request, 'todo/categories.html', {'categories': categories, 'form': form})

# 分类筛选
@login_required
def filter_by_category(request, category_id):
    if category_id == 0:
        # 处理"未分类"的情况
        todos = Todo.objects.filter(user=request.user, category__isnull=True)
        current_category = {'name': '未分类'}  # 用于在模板中显示标题
    else:
        # 处理普通分类
        category = get_object_or_404(Category, pk=category_id, user=request.user)
        todos = Todo.objects.filter(user=request.user, category=category)
        current_category = category
    return render(request, 'todo/index.html', {'todos': todos, 'current_category': current_category})

# 搜索功能
@login_required
def search_todos(request):
    query = request.GET.get('q')
    if query:
        todos = Todo.objects.filter(
            user=request.user,
            title__icontains=query
        )
    else:
        todos = Todo.objects.filter(user=request.user)
    return render(request, 'todo/index.html', {'todos': todos, 'search_query': query})


@login_required
def delete_category(request, category_id):
    category = get_object_or_404(Category, pk=category_id, user=request.user)

    # 检查分类下是否有任务
    if Todo.objects.filter(category=category).exists():
        messages.error(request, "该分类下还有任务，不能删除！")
        return redirect('manage_categories')

    category.delete()
    messages.success(request, "分类已成功删除！")
    return redirect('manage_categories')

@login_required
def toggle_completed(request, todo_id):
    todo = get_object_or_404(Todo, pk=todo_id, user=request.user)
    todo.completed = not todo.completed
    todo.save()
    return redirect('index')

@login_required
def task_report(request):
    # 获取当前月份
    today = datetime.date.today()
    year = today.year
    month = today.month

    # 查询当前用户、当前月份已完成的任务，并按周分组计数
    completed_todos = Todo.objects.filter(
        user=request.user,
        completed=True,
        created_time__year=year,
        created_time__month=month
    ).annotate(
        week=TruncWeek('created_time')
    ).values('week').annotate(
        count=Count('id')
    ).order_by('week')

    # 准备图表数据
    labels = [f"第 {item['week'].isocalendar()[1]} 周" for item in completed_todos]
    data = [item['count'] for item in completed_todos]

    graphic = None
    if data:
        plt.figure(figsize=(10, 5))
        plt.bar(labels, data, color='#007bff')
        plt.title(f'{year}年{month}月任务完成情况（按周）')
        plt.ylabel('完成任务数')
        plt.xlabel('周')
        plt.xticks(rotation=45)
        plt.tight_layout()

        buffer = io.BytesIO()
        plt.savefig(buffer, format='png')
        buffer.seek(0)
        image_png = buffer.getvalue()
        buffer.close()
        plt.close()

        graphic = base64.b64encode(image_png).decode('utf-8')

    context = {
        'graphic': graphic,
        'year': year,
        'month': month
    }
    return render(request, 'todo/report.html', context)

@login_required
def manage_templates(request):
    if request.method == 'POST':
        form = TaskTemplateForm(request.POST)
        if form.is_valid():
            template = form.save(commit=False)
            template.user = request.user
            template.save()
            messages.success(request, '任务模板已成功创建！')
            return redirect('manage_templates')
    else:
        form = TaskTemplateForm()

    templates = TaskTemplate.objects.filter(user=request.user)
    context = {
        'form': form,
        'templates': templates
    }
    return render(request, 'todo/manage_templates.html', context)

@login_required
def delete_template(request, template_id):
    template = get_object_or_404(TaskTemplate, pk=template_id, user=request.user)
    template.delete()
    messages.success(request, '任务模板已成功删除！')
    return redirect('manage_templates')

@login_required
def calendar_view(request):
    undated_todos = Todo.objects.filter(user=request.user, due_date__isnull=True)
    return render(request, 'todo/calendar.html', {'undated_todos': undated_todos})

@login_required
def todo_api(request):
    todos = Todo.objects.filter(user=request.user, due_date__isnull=False)
    events = []
    for todo in todos:
        priority_val = str(todo.priority)
        color = '#28a745' # 默认为低优先级（绿色）
        if priority_val == '3' or priority_val == 'H':
            color = '#dc3545' # 高（红色）
        elif priority_val == '2' or priority_val == 'M':
            color = '#ffc107' # 中（黄色）

        events.append({
            'title': todo.title,
            'start': todo.due_date.isoformat(),
            'id': todo.id,
            'color': color,
            'url': f'/edit/{todo.id}/' # 点击事件跳转到编辑页
        })
    return JsonResponse(events, safe=False)